from demo.chapter04.models.model import Goods, Supplier
from demo.chapter04.data import goods_list, supplier_list


def save_model():
    supplier = Supplier()
    supplier.name = "淘宝"
    supplier.address = "杭州市"
    supplier.phone = "18888888888"
    supplier.save()
    print(supplier.id)


def data_import():
    for item in supplier_list:
        supplier = Supplier(**item)
        supplier.save()
        print(supplier.id)

    for item in goods_list:
        goods = Goods(**item)
        goods.save()
        print(goods.id)


def query_model():
    # 获取某一条数据
    # good = Goods.get(Goods.id == 2)
    # good = Goods.get_by_id(2)
    # good = Goods[2]     # ==>  __getitem__
    # print(good.name)

    # 获取多条数据
    # goods = Goods.select()     # ==> 返回的是modelselect对象（并没有查询数据库），当for循环的时候才会去执行

    # select name,price from goods where price>100
    # goods = Goods.select(Goods.name,Goods.price).where(Goods.price>100)

    # select name,price from goods where price>100 and click_num > 200
    # goods = Goods.select(Goods.name,Goods.price).where((Goods.price>100)&(Goods.click_num>200))

    # select name,price from goods where price>100 or click_num > 200
    # goods = Goods.select(Goods.name,Goods.price).where((Goods.price>100)|(Goods.click_num>200))

    # select name,price from goods where name like "%飞天"
    # goods = Goods.select(Goods.name, Goods.price).where(Goods.name.contains("飞天"))

    # select * from goods where id in (2,4)
    # goods = Goods.select().where(Goods.id << [2,4])
    # goods = Goods.select().where((Goods.id==2)|(Goods.id==4))
    # goods = Goods.select().where(Goods.id.in_([2,4])) # ==> 推荐

    # ==> http://docs.peewee-orm.com/en/latest/peewee/query_operators.html

    # select * from goods where price>click_num
    # goods = Goods.select().where(Goods.price > Goods.click_num)

    # 排序
    # select * from goods order by price desc
    # goods = Goods.select().order_by(Goods.price.desc())
    # goods = Goods.select().order_by(-Goods.price)

    # 分页
    # 123456
    # paginate(1,2)  从第1页开始，取两条数据 => 65
    # paginate(2,2)  从第2页开始，取两条数据 => 43
    goods = Goods.select().order_by(-Goods.id).paginate(2, 2)
    for good in goods:
        print(good.id, good.name, good.price, good.click_num)
    pass


def update_model():
    # sep1
    # good = Goods.get_by_id(2)
    # good.click_num += 1
    # good.save()

    Goods.update(click_num=100).where(Goods.id == 2).execute()
    Goods.update(click_num=Goods.click_num + 1).where(Goods.id == 2).execute()


def del_model():
    # good = Goods.get_by_id(6) # => select方法如果没有数据则为空，get如果没有数据则会抛异常，需要注意
    # good.delete_instance()

    Goods.delete().where(Goods.id > 6).execute()


if __name__ == '__main__':
    del_model()
